package cc.vv.party.web;


import cc.vv.party.beans.model.Org
import cc.vv.party.beans.model.OrgAdmin
import cc.vv.party.beans.vo.NodeVO
import cc.vv.party.beans.vo.OrgVO
import cc.vv.party.common.base.BaseController
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.constants.SysConsts
import cc.vv.party.common.constants.enums.RoleType
import cc.vv.party.common.wrapper.ResponseEntityWrapper
import cc.vv.party.exception.BizException
import cc.vv.party.logger.annotation.OperateLog
import cc.vv.party.param.OrgEditParam
import cc.vv.party.param.OrgParam
import cc.vv.party.service.OrgService
import cc.vv.party.param.OrgIntroductionParam
import cc.vv.party.service.OrgAdminService
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiImplicitParams
import io.swagger.annotations.ApiOperation
import org.apache.ibatis.annotations.Param
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Validated
@RestController
@Api(value = "组织机构", tags = ["组织机构服务端API"], description = "组织机构服务端API-服务端组织机构相关接口")
@RequestMapping("/web/org")
class OrgController : BaseController() {

    @Autowired
    lateinit var orgService: OrgService

    @Autowired
    lateinit var orgAdminService: OrgAdminService

    @ApiOperation(value = "保存组织机构", notes = "保存组织机构")
    @PostMapping("/save")
    @OperateLog(content = "添加组织机构")
    fun addOrg(@Validated @RequestBody org: OrgParam): ResponseEntityWrapper<OrgVO> {
        return success(orgService.addOrg(org, getCurrentUserId(), getCurrentUserAccount()))
    }

    @ApiOperation(value = "组织机构列表", notes = "组织机构列表")
    @GetMapping("/list")
    @OperateLog(content = "查看组织结构列表")
    fun orgList(): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgList())
    }

    @ApiOperation(value = "组织机构管理-组织机构列表", notes = "组织机构列表")
    @GetMapping("/list-with-auth")
    @OperateLog(content = "查看组织结构列表")
    fun orgListWithAuth(): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getManagedOrgList(getCurrentUserAccount()))
    }

    @ApiOperation(value = "组织机构详情", notes = "组织机构详情")
    @OperateLog(content = "查看组织结构详情")
    @GetMapping("/detail")
    fun orgDetail(@RequestParam id: String): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgDetailById(id))
    }

    @ApiOperation(value = "更新组织机构信息", notes = "更新组织机构信息")
    @OperateLog(content = "更新组织机构信息")
    @PostMapping("/edit")
    fun editOrg(@Validated @RequestBody org: OrgEditParam): ResponseEntityWrapper<OrgVO> {
        return success(orgService.updateOrg(org, getCurrentUserId(), getCurrentUserAccount()))
    }

    @ApiOperation(value = "删除组织机构", notes = "删除组织机构")
    @GetMapping("/delete")
    @OperateLog(content = "删除组织机构")
    fun deleteOrg(@RequestParam orgId: String): ResponseEntityWrapper<OrgVO> {
        return success(orgService.deleteOrg(orgId, getCurrentUserAccount()))
    }

    @ApiOperation(value = "更新组织机构简介", notes = "更新组织机构简介")
    @PostMapping("/update/introduction")
    @OperateLog(content = "更新组织机构简介")
    fun updateIntroduction(@Validated @RequestBody param: OrgIntroductionParam): ResponseEntityWrapper<OrgVO> {
        val org = orgService.selectById(param.id)
        org.introduction = param.introduction
        return if (orgService.updateById(org)) success(org.transfer()) else error(StatusCode.ERROR.statusCode, "更新失败")
    }

    @ApiOperation(value = "更新宝塔区简介", notes = "更新宝塔区简介")
    @PostMapping("/update/bt-intro")
    @OperateLog(content = "更新宝塔区简介")
    fun updateAreaIntro(@RequestBody intro: String): ResponseEntityWrapper<OrgVO> {
        val org = getOrg()
        org.introduction = intro
        return if (orgService.updateById(org)) success(org.transfer()) else error(StatusCode.ERROR.statusCode, "更新失败")
    }

    @ApiOperation(value = "获取宝塔区简介", notes = "获取宝塔区简介")
    @PostMapping("/bt-intro")
    fun getAreaIntro(): ResponseEntityWrapper<OrgVO> {
        val org = getOrg()
        return success(org.transfer())
    }

    @ApiOperation(value = "获取某一个类型的组织机构列表")
    @ApiImplicitParam(
        name = "type",
        value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户，9:支部，10:街道联席会议，11:四支队伍，12:非公党建，13:社区大党委)"
    )
    @GetMapping("/org-list-by-type")
    fun orgListByType(@RequestParam type: List<Int>): ResponseEntityWrapper<List<OrgVO>> {
        return success(
            orgService.selectList(
                EntityWrapper<Org>().`in`(
                    "type",
                    type
                )
            ).transferEntries<OrgVO>() as List<OrgVO>
        )
    }

    @ApiOperation(value = "获取指定子集类型组织列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "parentId", value = "父级编号", required = true),
            ApiImplicitParam(
                name = "type",
                value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户)",
                required = true
            )
        ]
    )
    @GetMapping("/child-type-list")
    fun findChildTypeList(@RequestParam parentId: String, @RequestParam type: Int): ResponseEntityWrapper<List<OrgVO>> {
        var list = orgService.selectList(EntityWrapper<Org>().where("p_id = {0}", parentId).and("type = {0}", type))
            ?: emptyList()
        return success(list.transferEntries<OrgVO>() as ArrayList)
    }

    @ApiOperation(value = "获取指定父级下指定子集类型集合的组织列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "parentId", value = "父级编号", required = true),
            ApiImplicitParam(
                name = "types",
                value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户)",
                dataType = "Array",
                required = true
            )
        ]
    )
    @GetMapping("/child-types-list")
    fun findChildTypesList(@RequestParam parentId: String, @RequestParam types: List<Int>): ResponseEntityWrapper<List<OrgVO>> {
        var list = orgService.selectList(EntityWrapper<Org>().where("p_id = {0}", parentId).and().`in`("type", types))
            ?: emptyList()
        return success(list.transferEntries<OrgVO>() as ArrayList)
    }

    @ApiOperation(value = "获取指定组下所有指定子集类型集合的组织列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "id", value = "编号", required = true),
            ApiImplicitParam(
                name = "types",
                value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户)",
                dataType = "Array",
                required = true
            )
        ]
    )
    @GetMapping("/child-all-type-list")
    fun findAllChildTypesList(@RequestParam id: String, @RequestParam types: List<Int>): ResponseEntityWrapper<List<OrgVO>> {
        var list =
            orgService.selectList(EntityWrapper<Org>().like("path", "%$id%").and("id != {0}", id).`in`("type", types))
                ?: emptyList()
        return success(list.transferEntries<OrgVO>() as ArrayList)
    }

    /**
     * 获取当前用户所管理的组织结构列表及子集合列表
     */
    @ApiOperation(value = "获取当前管理员所管理的组织机构及所有子集", notes = "获取当前管理员所管理的组织机构及所有子集")
    @PostMapping("/manage-org-list-with-children")
    fun userManageOrgListAndChildren(): ResponseEntityWrapper<List<OrgVO>> {
        return success(orgService.findUserOrgAndChildren(getCurrentUserAccount()))
    }

    /**
     * 获取当前用户所管理的组织结构列表
     */
    @ApiOperation(value = "获取当前管理员所管理的组织机构", notes = "获取当前管理员所管理的组织机构")
    @PostMapping("/manage-org-list")
    fun userManageOrgList(): ResponseEntityWrapper<List<OrgVO>> {
        return success(orgService.findOrgByUserAccount(getCurrentUserAccount()))
    }

    /**
     * 获取数据库中默认的宝塔区组织机构
     */
    private fun getOrg(): Org {
        return orgService.selectById(SysConsts.BAOTA_AREA_ID)
    }


    @ApiOperation(value = "获取党组织机构列表", notes = "获取党组织机构列表")
    @ApiImplicitParams(
        value = [ApiImplicitParam(name = "type", value = "节点类型", required = false),
            ApiImplicitParam(name = "nodeId", value = "节点Id", required = false)]
    )
    @GetMapping("/party-node-list")
    fun partyNodeList(
        @RequestParam(required = false) type: String?,
        @RequestParam(required = false) nodeId: String?
    ): ResponseEntityWrapper<List<NodeVO>> {
        return success(orgService.findPartyNode(type, nodeId))
    }


    @ApiOperation(value = "保存党建简介", notes = "保存党建简介")
    @PostMapping("/save-party-introduction")
    @OperateLog(content = "保存党建简介")
    fun partyIntroduction(@RequestBody content: String): ResponseEntityWrapper<Boolean> {
        var entity = orgService.selectById(SysConsts.BAOTA_AREA_ID)
            ?: throw BizException(StatusCode.FIELD_VALUE_ERROR.statusCode, "区信息不存在")
        entity.partyIntroduction = content
        return success(entity.updateById())
    }

    @ApiOperation(value = "获取党建简介", notes = "获取党建简介")
    @PostMapping("/get-party-introduction")
    @OperateLog(content = "获取党建简介")
    fun getPartyIntroduction(): ResponseEntityWrapper<String> {
        var entity = orgService.selectById(SysConsts.BAOTA_AREA_ID)
            ?: throw BizException(StatusCode.FIELD_VALUE_ERROR.statusCode, "区信息不存在")
        return success(entity.partyIntroduction)
    }

    @ApiOperation(value = "获取指定社区下的单位列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "communityId", value = "社区编号", required = true)
        ]
    )
    @GetMapping("/unit-list")
    fun findUnitList(@RequestParam communityId: String): ResponseEntityWrapper<List<OrgVO>> {
//        val currentRole =
//            getCurrentUserRole().find { it.type == RoleType.SECTION_ADMIN || it.type == RoleType.UNIT_ADMIN }
//                ?: throw BizException(StatusCode.FORBIDDEN.statusCode, "只能社区和单位管理员可以进行操作")
        val result =
//            when {
//                currentRole.type == RoleType.SECTION_ADMIN ->
                    orgService.selectList(
                    EntityWrapper<Org>().where(
                        "p_id = {0}",
                        communityId
                    ).and().eq("type", "4")
                ) ?: emptyList()
//                currentRole.type == RoleType.UNIT_ADMIN -> {
//                    val orgAdmin =
//                        orgAdminService.selectOne(EntityWrapper<OrgAdmin>().eq("user_account", getCurrentUserAccount()))
//                    orgService.selectList(
//                        EntityWrapper<Org>().where("id = {0}", orgAdmin.orgId).and().eq(
//                            "type",
//                            "4"
//                        ).eq("p_id", communityId)
//                    )
//                }
//                else -> throw BizException(StatusCode.FORBIDDEN.statusCode, "只能社区和单位管理员可以进行操作")
//            }

        return success(result.transferEntries<OrgVO>() as ArrayList)
    }

}
